using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Inovance.InoMotionCotrollerShop.InoServiceContract.EtherCATConfigApi;
using Inovance_GR10_2HCE_UserCtrl;

namespace example
{
    public partial class Form1 : Form
    {
        public List<int> mCaptPosList;
        public static UInt64 cardHandle;//轴卡操作句柄
        UInt32 retRtn; //函数接口返回值
        Int16 axNo = 0;//轴号
        Int16 count = 1;//轴数
        Int16 stopType = 1;//停止类型 0： 平滑停止 1： 急速停止
        Int16 station_id = 0;//从站站点
        short chanel = 0;//计数器通道，取值范围[0,1]
        public Form1()
        {
            InitializeComponent();
        }

        #region 初始化
        //打印日志
        private void ShowMessage(string msg)
        {
            listBox_RunSts.Items.Add(DateTime.Now.ToString() + " " + msg);
            listBox_RunSts.SelectedIndex = listBox_RunSts.Items.Count - 1;
            listBox_RunSts.SelectedIndex = -1;
        }        
        //卡初始化
        private void button_CardInit_Click(object sender, EventArgs e)
        {
            UInt32 masterStatus = 0;
            int cardNo = 0; //打开0号卡
            Int32 cardsNum = 0;
            try
            {
                //非必须步骤，读取电脑中轴卡的数量
                retRtn = ImcApi.IMC_GetCardsNum(ref cardsNum);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_GetCardsNum failed 故障代码为：0x" + retRtn.ToString("x8"));
                }
                textBox_CardNum.Text = cardsNum.ToString();
                //【1】获取轴卡操作句柄
                retRtn = ImcApi.IMC_OpenCardHandle(cardNo, ref cardHandle);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_OpenCardHandle failed 故障代码为：0x" + retRtn.ToString("x8"));
                }
                //【2】获取主站状态
                retRtn = ImcApi.IMC_GetECATMasterSts(cardHandle, ref masterStatus);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_GetECATMasterSts failed 故障代码为：0x" + retRtn.ToString("x8"));
                }
                else
                {
                    if (masterStatus != ImcApi.EC_MASTER_OP)
                    {
                        //【3】下载设备参数
                        //deviceconfig.xml文件是由控制卡后台软件配置生成然后手动放到编译路径下，路径可自由选择；
                        retRtn = ImcApi.IMC_DownLoadDeviceConfig(cardHandle, "Deviceconfig.xml");
                       // retRtn = ImcApi.IMC_DownLoadDeviceConfig(cardHandle, ".\\deviceconfig.xml");
                        if (retRtn != ImcApi.EXE_SUCCESS)
                        {
                            ShowMessage("IMC_DownLoadDeviceConfig failed 故障代码为：0x" + retRtn.ToString("x8"));
                        }
                        //【4】启动总线
                        retRtn = ImcApi.IMC_ScanCardECAT(cardHandle, 1);            //0表示非阻塞式开卡，1表示阻塞式开卡；
                        if (retRtn != ImcApi.EXE_SUCCESS)
                        {
                            ShowMessage("IMC_ScanCardECAT failed 故障代码为：0x" + retRtn.ToString("x8"));
                        }
                        //【5】下载系统参数
                        //systemconfig.xml文件是由控制卡后台软件配置生成然后手动放到编译路径下，路径可自由选择；
                        retRtn = ImcApi.IMC_DownLoadSystemConfig(cardHandle, "Systemconfig.xml");
                        //retRtn = ImcApi.IMC_DownLoadSystemConfig(cardHandle, ".\\systemconfig.xml");
                        if (retRtn != ImcApi.EXE_SUCCESS)
                        {
                            ShowMessage("IMC_DownLoadSystemConfig failed 故障代码为：0x" + retRtn.ToString("x8"));
                        }
                    }
                }
                timer_UI.Enabled = true;
                textBox_CardNum.Text = cardsNum.ToString();
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }
        //关闭卡
        private void button_CloseCard_Click(object sender, EventArgs e)
        {
            try
            {
                timer_UI.Enabled = false;

                if (textBox_CounterSts0.Text == "1")
                {
                    retRtn = GR10_2HCE_UserCtrl.IMC_2HCE_StopCounter(cardHandle, 0, 0);
                    if (retRtn != ImcApi.EXE_SUCCESS)
                    {
                        ShowMessage("IMC_2HCE_StopCounter failed 故障代码为：0x" + retRtn.ToString("x8"));
                        return;
                    }
                }

                retRtn = ImcApi.IMC_CloseCard(cardHandle);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage(System.Reflection.MethodBase.GetCurrentMethod().Name + " failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }
        #endregion

        #region 控制
        //使能
        private void button_AxServoOn_Click(object sender, EventArgs e)
        {
            try
            {
                retRtn = ImcApi.IMC_AxServoOn(cardHandle, axNo, count);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage(System.Reflection.MethodBase.GetCurrentMethod().Name + " failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
                else
                {
                    ShowMessage("轴上使能成功");

                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }
        //下使能
        private void button_AxServoOff_Click(object sender, EventArgs e)
        {
            try
            {
                retRtn = ImcApi.IMC_AxServoOff(cardHandle, axNo, count);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage(System.Reflection.MethodBase.GetCurrentMethod().Name + " failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
                else
                {
                    ShowMessage("轴下使能成功");
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }
        //停止
        private void button_AxMoveStop_Click(object sender, EventArgs e)
        {
            try
            {
                stopType = 1;//停止类型 0： 平滑停止 1： 急速停止
                retRtn = ImcApi.IMC_AxMoveStop(cardHandle, axNo, stopType);// 0平滑停止；1 急停停止
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage(System.Reflection.MethodBase.GetCurrentMethod().Name + " failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }

            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }
        //清除轴状态
        private void button_ClrAxSts_Click(object sender, EventArgs e)
        {
            try
            {
                for (Int16 i = axNo; i < count; i++)
                {
                    retRtn = ImcApi.IMC_ClrAxSts(cardHandle, i);
                }
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage(System.Reflection.MethodBase.GetCurrentMethod().Name + " failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }

        private void button_StartJogMoveF_Click(object sender, EventArgs e)
        {
            double tgVel = Convert.ToDouble(textBox_JogVel.Text);
            try
            {
                retRtn = ImcApi.IMC_StartJogMove(cardHandle, axNo, tgVel);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_StartJogMove failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }

        private void button_StartJogMoveB_Click(object sender, EventArgs e)
        {
            double tgVel = -Convert.ToDouble(textBox_JogVel.Text);
            try
            {
                retRtn = ImcApi.IMC_StartJogMove(cardHandle, axNo, tgVel);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_StartJogMove failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }


            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }

        #endregion

        #region 轴状态与信息显示
        //将十进制整形转换为二进制显示的字符串
        private string ConvertDecimalToBinary(Int32 nAxSts) 
        {
            string strAxSts = "";
            Int32 nBitValue = 0x00;

            for (uint i = 0; i < 11; i++)
            {
                nBitValue = (Int32)(0x01 * Math.Pow(2.0, i));    //对nBitValue向左移1位，移到第几位通过i来控制
                if ((nAxSts & nBitValue) == nBitValue)
                {
                    strAxSts = "1" + strAxSts;
                }
                else
                {
                    strAxSts = "0" + strAxSts;
                }
            }
            return strAxSts;
        }
        //UI界面信息刷新
        private void timer_UI_Tick(object sender, EventArgs e)
        {
            
                //timer_UI.Enabled = false;
                double[] PrfPosArray = { 0,0 };
                double[] EncPosArray = { 0,0 };
                double[] EncVelArray = { 0,0 };
                Int32[] AxStsArray = { 0,0 };
                Int16 CtrlMode = 0;
                short CounterSts = 0;//计数器状态，0：计数器停止计数  1：计数器正常计数
                Int32 Value = 0;//计数器通道当前计数值

                //获取目标位置
                retRtn = ImcApi.IMC_GetAxPrfPos(cardHandle, axNo, PrfPosArray, count);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_GetAxSts failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
                //获取反馈位置
                retRtn = ImcApi.IMC_GetAxEncPos(cardHandle, axNo, EncPosArray, count);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_GetAxEncPos failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
                //获取反馈速度
                retRtn = ImcApi.IMC_GetAxEncVel(cardHandle, axNo, EncVelArray, count);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_GetAxSts failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
                //获取伺服状态
                retRtn = ImcApi.IMC_GetAxSts(cardHandle, axNo, AxStsArray, count);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_GetAxSts failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
               
                //获取伺服控制模式
                retRtn = ImcApi.IMC_GetAxCtrlMode(cardHandle, axNo, ref CtrlMode);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_GetAxCtrlMode failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
                //X轴状态显示
                textBox_AxPrfPos0.Text = PrfPosArray[0].ToString();
                textBox_AxEncPos0.Text = EncPosArray[0].ToString();
                textBox_AxEncVel0.Text = EncVelArray[0].ToString();
                //转化为二进制字符串显示
                textBox_AxSts0.Text = ConvertDecimalToBinary(AxStsArray[0]);

                //到位信号判断
                textBox_AxStsArrive0.Text = (AxStsArray[0] & 0xC) == 0x8 ? "1" : "0";
                textBox_CtrlMode.Text = CtrlMode.ToString();

                //计数器状态读取
                retRtn = GR10_2HCE_UserCtrl.IMC_2HCE_GetCounterSts(cardHandle, station_id, chanel, ref CounterSts, ref Value);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_2HCE_GetCounterSts0 failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
                textBox_CounterSts0.Text = CounterSts.ToString();
                textBox_Value0.Text = Value.ToString();
        
        }
        #endregion    
        
        #region 计数功能通道 0 测试        
        //配置计数器
        private void button_2HCE_CounterConfig_Click(object sender, EventArgs e)
        {
            short mode = 1;//计数器类型，0：线型  1：环型；
            short dir = 0;//计数方向，0：A相优先  1：B相优先；
            short type = 3;//计数器类型 0：AB相1倍频  1：AB相2倍频  2：AB相4倍频  3：脉冲+方向  4：CW/CCW
            int maxCnt = 100000;//计数通道最大计数值 默认：2147483647
            int minCnt = -100000;//计数通道最小计数值 默认：-2147483647
            UInt32 abort_code=0;
            Byte[] data = { 0, 0, 0, 0, 0, 0, 0, 0 };

            //写计数通道最大计数值
            data = BitConverter.GetBytes(maxCnt);
            retRtn = ImcApi.IMC_SetEcatSdo(cardHandle, station_id, 0x3103, 1, data, 4, ref abort_code);
            if (retRtn != ImcApi.EXE_SUCCESS)
            {
                ShowMessage("IMC_SetEcatSdo failed 故障代码为：0x" + retRtn.ToString("x8"));
                return;
            }

            //写计数通道最小计数值
            data = BitConverter.GetBytes(minCnt);
            retRtn = ImcApi.IMC_SetEcatSdo(cardHandle, station_id, 0x3104, 1, data, 4, ref abort_code);
            if (retRtn != ImcApi.EXE_SUCCESS)
            {
                ShowMessage("IMC_SetEcatSdo failed 故障代码为：0x" + retRtn.ToString("x8"));
                return;
            }

            retRtn = GR10_2HCE_UserCtrl.IMC_2HCE_CounterConfig(cardHandle, station_id, chanel, mode, dir, type);
            if (retRtn != ImcApi.EXE_SUCCESS)
            {
                ShowMessage("IMC_2HCE_CounterConfig failed 故障代码为：0x" + retRtn.ToString("x8"));
                return;
            }
        }
        //启动计数
        private void button_2HCE_UserCtrl_Click(object sender, EventArgs e)
        {
            try
            {
                retRtn = GR10_2HCE_UserCtrl.IMC_2HCE_StartCounter(cardHandle, 0, 0);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_2HCE_StartCounter failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }
        //停止计数
        private void button_2HCE_StopCounter_Click(object sender, EventArgs e)
        {
            try
            {
                retRtn = GR10_2HCE_UserCtrl.IMC_2HCE_StopCounter(cardHandle, 0, 0);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_2HCE_StopCounter failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }
        //清除计数
        private void button_2HCE_UserCtrl(object sender, EventArgs e)
        {
            try
            {
                retRtn = GR10_2HCE_UserCtrl.IMC_2HCE_ClearCounter(cardHandle, 0, 0);
                if (retRtn != ImcApi.EXE_SUCCESS)
                {
                    ShowMessage("IMC_2HCE_ClearCounter failed 故障代码为：0x" + retRtn.ToString("x8"));
                    return;
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.ToString());
            }
        }
      
        #endregion
              
    }
}
